<?php

namespace App\Http\Controllers\Service;

use App\Http\Controllers\Service\ServiceController;
use Illuminate\Http\Request;
use App\Http\Components\UserComponent;

use App\Models\ServiceModel;
use App\Models\UserProfileModel;
use App\Models\UserSettingModel;
use App\Models\DataConfigModel;
use App\Models\LogUserPositionModel;
use App\library\UploadFile;
use App\library\UtilFunction;


/**
 * 发现男神女神
 */
class FindController extends ServiceController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->find($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 发现男神女神
     */
    public function find(Request $request){
        $customAttr = [
            'lon' => '经度',
            'lat' => '纬度',
        ];
        $this->validate($request, [
            'lon' => 'required',
            'lat' => 'required',
        ],[ ], $customAttr);
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $active_time = $request->input('active_time');
        if(empty($active_time)){
            $active_time = '60+';
        }
        $lon = $request->input('lon');
        $lat = $request->input('lat');
        //获取配置信息
        $dataConfig = new DataConfigModel();
        $find_distance = $dataConfig->get_value('find_distance');   //获取显示距离范围
        $alive_time_limit = $dataConfig->get_value('alive_time_limit');//多少小时不活跃则不显示
        //结果集返回
        $find_user_list = array();
        $find_user_id = array();
        $find_user_distance = array();
        //上报用户地理位置
        $userSetting = UserSettingModel::where("user_id",$user_id)->first();
        $userSetting->lon = $lon;
        $userSetting->lat = $lat;
        $userSetting->actived_at = time();
        $result = $userSetting->saveOrFail();
        if($result){
            //记录地理位置日志
            $LogUserPosition = new LogUserPositionModel();
            $LogUserPosition->user_id = $user_id;
            $LogUserPosition->lon = $lon;
            $LogUserPosition->lat = $lat;
            $LogUserPosition->saveOrFail();

            //筛选出时间范围内的用户
            if(strstr($active_time,'+')){
                $user_list = UserSettingModel::where('actived_at','>',time()-(3600*$alive_time_limit))->where('user_id','!=',$user_id)->where('seller_limit_time','<',time())->where("switch_service",1)->get();
            }else{
                $user_list = UserSettingModel::where("actived_at",">",time()-10*60)->where('actived_at','>',time()-(3600*$alive_time_limit))->where('user_id','!=',$user_id)->where('seller_limit_time','<',time())->where("switch_service",1)->get();
            }

            if($user_list){
                $user_list = $user_list->toArray();

                foreach($user_list AS $uitem){
                    $distance = UtilFunction::get_distance($lat,$lon,$uitem['lat'],$uitem['lon']);
                    if($distance <= ($find_distance*1000)){
                        //获取距离范围内的用户ID
                        $find_user_id[] = $uitem['user_id'];
                        $find_user_distance[$uitem['user_id']] = $distance;
                    }
                }

                $userProfile = UserProfileModel::where('user_id',$user_id)->first()->toArray();
                //拉去用户数据
                if(!empty($find_user_id)){
                    $active_user_list = UserProfileModel::select([
                        'user_profile.user_id',
                        'user_profile.avatar',
                        'user_profile.nick_name',
                        'user_profile.job',
                        'user_profile.age',
                        'user_profile.gender',
                        'user_profile.constellation',
                        'user_profile.height',
                        'user_profile.weight',
                        'user_profile.star',

                        'user_setting.lon',
                        'user_setting.lat',
                        'user_setting.actived_at',

                        'user_service.price',
                        'user_service.advantage',
                        'user_service.content',
                        'user_service.pictures',

                    ])
                        ->where('user.app_login_time','!=','0000-00-00 00:00:00')   //已退出登录不再显示
                        ->where('user_setting.switch_service',1)            //关闭服务不再显示
                        ->where('user_profile.gender','!=',$userProfile['gender'])            //只匹配异性
                        ->whereIn('user_profile.user_id', $find_user_id)
                        ->leftJoin('user_setting','user_setting.user_id','=','user_profile.user_id')
                        ->leftJoin('user_service','user_service.user_id','=','user_profile.user_id')
                        ->leftJoin('user','user.user_id','=','user_profile.user_id')
                        ->get();
                    if($active_user_list){
                        $active_user_list = $active_user_list->toArray();
                        foreach($active_user_list AS &$litem){
                            //头像
                            $litem['avatar'] = UserComponent::get_avatar($litem['avatar']);
                            //服务内容 第一张图
                            $sevice_pictures = explode(',',$litem['pictures']);
                            $litem['service_picture'] = $sevice_pictures[0];
                            //距离
                            $distance = $find_user_distance[$litem['user_id']];
                            $litem['distance_true'] = $distance;
                            if($distance<1000){
                                $distance = $distance."米";
                            }else{
                                $distance = round(($distance/1000),2)."公里";
                            }
                            $litem['distance'] = $distance;
                            $litem['actived_at'] = UtilFunction::get_active_time(time()-$litem['actived_at']);
                            unset($litem['pictures']);
                        }
                        $find_user_list = $active_user_list;
                    }
                }
            }

            if($find_user_list){
                /*根据实际距离排序*/
                 foreach ( $find_user_list as $key => $row ){
                    $sort_keys[$key] = $row['distance_true'];
                }

                array_multisort($sort_keys, SORT_ASC, $find_user_list);
                return $this->json('1','用户数据获取成功',$find_user_list);
            }else{
                echo json_encode(array('status'=>'1','message'=>'没有符合条件的用户','data'=>array()),JSON_UNESCAPED_UNICODE);
            }

        }else{
            return $this->json('0','地理位置上报失败');

        }

    }
}